<template>
  <div class="app-container">
    <div class="data-content">
      <div v-has-perm="['nljs_indicator_category_view']" class="left">
        <div style="text-align: center">
          <el-input
            v-model="searchName"
            style="width: 240px"
            size="large"
            placeholder="请输入分类名称"
            :suffix-icon="Search"
          />
        </div>
        <div>
          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :props="treeProps"
            :expand-on-click-node="false"
            style="margin-top: 20px"
            @node-click="nodeClick"
          />
        </div>
      </div>
      <div v-has-perm="['nljs_indicator_view']" class="right" style="padding: 15px">
        <div>
          <div class="title-area">
            <div style="width: 100%; margin-top: 15px">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item prop="name" label="指标">
                  <el-input
                    v-model="queryParams.name"
                    placeholder="指标名称"
                    clearable
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                  <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
                  <el-button type="primary" plain :icon="Plus" @click="addForm">新增指标</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column label="名称" prop="name" min-width="150" />
            <el-table-column label="编码" prop="code" min-width="120" />
            <el-table-column label="描述" prop="description" min-width="150" />
            <!-- <el-table-column label="附件ID列表" prop="attachmentIds" width="140" /> -->
            <el-table-column label="状态" prop="status" width="120">
              <template #default="scope">
                <el-tag :type="statusTag[scope.row.status]">
                  {{ statusMap[scope.row.status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="180" />
            <el-table-column label="创建人" prop="createBy" width="140" />
            <el-table-column fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-button
                  v-has-perm="['nljs_indicator_edit']"
                  link
                  type="success"
                  :icon="Edit"
                  size="small"
                  @click="editCat(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  v-has-perm="['nljs_indicator_del']"
                  link
                  type="danger"
                  :icon="Delete"
                  size="small"
                  @click="delCat(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      :close-on-click-modal="false"
      @close="reset"
    >
      <div class="add">
        <el-form ref="formRef" :model="definitionForm" :rules="definitionRules" label-width="auto">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="指标名称" prop="name">
                <el-input v-model="definitionForm.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指标编码" prop="code">
                <el-input v-model="definitionForm.code" placeholder="请输入编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 统计维度 -->
              <el-form-item label="统计维度" prop="calculationCycle">
                <el-select v-model="definitionForm.calculationCycle" placeholder="请选择统计维度">
                  <el-option
                    v-for="item in calculationCycleType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 类型 -->
              <el-form-item label="类型" prop="categoryId">
                <el-tree-select
                  v-model="definitionForm.categoryId"
                  node-key="id"
                  :filterable="true"
                  :check-strictly="true"
                  :data="categoryTree"
                  :props="treeProps"
                  placeholder="请选择类型"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 计算方式 -->
              <el-form-item label="通用表单" prop="commonFormIds">
                <el-tree-select
                  v-model="definitionForm.commonFormIds"
                  collapse-tags
                  :collapse-tags-tooltip="true"
                  :max-collapse-tags="3"
                  :data="typeOptions"
                  :props="formTypeProps"
                  placeholder="请选择通用表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="燃煤表单" prop="coalFormIds">
                <el-tree-select
                  v-model="definitionForm.coalFormIds"
                  collapse-tags
                  :data="filterOptions"
                  :props="formTypeProps"
                  placeholder="请选择燃煤表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="水电表单" prop="waterElectricityFormIds">
                <el-tree-select
                  v-model="definitionForm.waterElectricityFormIds"
                  collapse-tags
                  :data="filterOptions"
                  :props="formTypeProps"
                  placeholder="请选择水电表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="光伏表单" prop="photovoltaicFormIds">
                <el-tree-select
                  v-model="definitionForm.photovoltaicFormIds"
                  collapse-tags
                  :data="filterOptions"
                  :props="formTypeProps"
                  placeholder="请选择光伏表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生物质表单" prop="biomassFormIds">
                <el-tree-select
                  v-model="definitionForm.biomassFormIds"
                  collapse-tags
                  :data="filterOptions"
                  :props="formTypeProps"
                  placeholder="请选择生物质表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="风电表单" prop="windPowerFormIds">
                <el-tree-select
                  v-model="definitionForm.windPowerFormIds"
                  collapse-tags
                  :data="filterOptions"
                  :props="formTypeProps"
                  placeholder="请选择风电表单"
                  node-key="id"
                  multiple
                  filterable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指标描述" prop="description">
                <el-input
                  v-model="definitionForm.description"
                  type="textarea"
                  maxlength="500"
                  :rows="2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="definitionForm.status">
                  <el-radio label="禁用" :value="0"></el-radio>
                  <el-radio label="启用" :value="1"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="default" @click="reset">取消</el-button>
          <el-button size="default" type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import FormAPI from '@/api/batch/form.api';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import IndiactorAPI from '@/api/batch/indicator.api';
// 指标分类
const searchName = ref('');
const categoryTree = ref<any>([]);
const currentCategoryId = ref<any>(undefined);
const treeProps = ref<any>({
  label: 'name',
  children: 'children',
});
const nodeClick = (data: any) => {
  currentCategoryId.value = data.id;
  handleQuery();
};
onBeforeMount(() => {
  IndiactorAPI.getIndicatorCategoryTree().then((data: any) => {
    categoryTree.value = data;
  });
});
// 统计维度类型: 年、月、季度、自定义
const calculationCycleType = reactive<any>([
  {
    label: '年',
    value: 'year',
  },
  {
    label: '月',
    value: 'month',
  },
  {
    label: '周',
    value: 'week',
  },
  {
    label: '季度',
    value: 'quarter',
  },
  {
    label: '自定义',
    value: 'custom',
  },
]);
const queryFormRef = ref<FormInstance>();
const pageTotal = ref(0);
const queryParams = reactive<any>({
  name: undefined,
});
const loading = ref(false);
const batchIds = ref<number[] | string[]>([]);
const tableData = ref<object[]>([]);
const statusTag: any = {
  0: 'danger',
  1: 'success',
};
const statusMap: any = {
  0: '禁用',
  1: '启用',
};
// const { params, query } = route;

const handleQuery = () => {
  loading.value = true;
  const params: any = {
    name: queryParams.name,
    categoryId: currentCategoryId.value,
  };
  IndiactorAPI.getIndicatorAllList(params)
    .then((data: any) => {
      tableData.value = data;
      loading.value = false;
    })
    .catch((err) => {
      console.error(err);
      loading.value = false;
    });
};

const dialogVisible = ref(false);
const dialogTitle = ref('新增');

const formRef = ref<FormInstance>();
const definitionForm = reactive<any>({
  id: undefined,
  name: '',
  code: '',
  calculationCycle: null,
  description: '',
  status: 1,
  commonFormIds: [],
  coalFormIds: [],
  waterElectricityFormIds: [],
  photovoltaicFormIds: [],
  biomassFormIds: [],
  windPowerFormIds: [],
  gasFormIds: [],
  energyStorageFormIds: [],
  cogenerationFormIds: [],
});
const definitionRules: FormRules = {
  name: [
    { required: true, message: '请输入指标名称', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入指标编码', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  commonFormIds: [{ required: true, message: '请选择表单', trigger: 'blur' }],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
};

const handleResetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

const handleSelectionChange = (val: any) => {
  batchIds.value = val.map((item: any) => item.id);
};

const editCat = (row: any) => {
  dialogVisible.value = true;
  dialogTitle.value = '修改指标';
  definitionForm.id = row.id;
  definitionForm.name = row.name;
  definitionForm.code = row.code;
  definitionForm.calculationCycle = row.calculationCycle;
  definitionForm.description = row.description;
  definitionForm.status = row.status;
  definitionForm.commonFormIds = row.commonFormIds ? row.commonFormIds.split(',') : [];
  definitionForm.coalFormIds = row.coalFormIds ? row.coalFormIds.split(',') : [];
  definitionForm.waterElectricityFormIds = row.waterElectricityFormIds
    ? row.waterElectricityFormIds.split(',')
    : [];
  definitionForm.photovoltaicFormIds = row.photovoltaicFormIds
    ? row.photovoltaicFormIds.split(',')
    : [];
  definitionForm.biomassFormIds = row.biomassFormIds ? row.biomassFormIds.split(',') : [];
  definitionForm.windPowerFormIds = row.windPowerFormIds ? row.windPowerFormIds.split(',') : [];
  definitionForm.gasFormIds = row.gasFormIds ? row.gasFormIds.split(',') : [];
  definitionForm.energyStorageFormIds = row.energyStorageFormIds
    ? row.energyStorageFormIds.split(',')
    : [];
  definitionForm.cogenerationFormIds = row.cogenerationFormIds
    ? row.cogenerationFormIds.split(',')
    : [];
  definitionForm.categoryId = row.categoryId;
};
const delCat = (row: any) => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      IndiactorAPI.delIndicator(row.id).then(() => {
        ElMessage.success('删除成功!');
        handleQuery();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

const addForm = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增指标';
};
const reset = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  definitionForm.id = undefined;
  definitionForm.description = '';
  definitionForm.status = 1;
  definitionForm.commonFormIds = [];
  definitionForm.coalFormIds = [];
  definitionForm.waterElectricityFormIds = [];
  definitionForm.photovoltaicFormIds = [];
  definitionForm.biomassFormIds = [];
  definitionForm.windPowerFormIds = [];
  definitionForm.gasFormIds = [];
  definitionForm.energyStorageFormIds = [];
  definitionForm.cogenerationFormIds = [];
  definitionForm.categoryId = null;
};
const confirm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const params = { ...definitionForm };
      params.commonFormIds = params.commonFormIds.join(',');
      params.coalFormIds = params.coalFormIds.join(',');
      params.waterElectricityFormIds = params.waterElectricityFormIds.join(',');
      params.photovoltaicFormIds = params.photovoltaicFormIds.join(',');
      params.biomassFormIds = params.biomassFormIds.join(',');
      params.windPowerFormIds = params.windPowerFormIds.join(',');
      params.gasFormIds = params.gasFormIds.join(',');
      params.energyStorageFormIds = params.energyStorageFormIds.join(',');
      params.cogenerationFormIds = params.cogenerationFormIds.join(',');
      if (definitionForm.id) {
        IndiactorAPI.editIndicator(params).then(() => {
          ElMessage.success('编辑成功!');
          reset();
          handleQuery();
        });
      } else {
        IndiactorAPI.addIndicator(params).then(() => {
          ElMessage.success('新增成功!');
          reset();
          queryParams.pageNum = 1;
          handleQuery();
        });
      }
    }
  });
};
const formTypeProps = {
  label: 'label',
  value: 'value',
  children: 'children',
};
const typeOptions = reactive<any>([]);
const filterOptions = computed(() => {
  const calculationCycleLabel =
    (definitionForm.calculationCycle &&
      calculationCycleType.find((item: any) => item.value === definitionForm.calculationCycle)
        .label) ||
    '';
  const selectedFormIds = definitionForm.commonFormIds;
  return typeOptions
    .map((item: any) => {
      const newItem = { ...item };
      if (newItem.children) {
        newItem.children = newItem.children.filter(
          (v: any) =>
            (!calculationCycleLabel || !v.tags || v.tags.include(calculationCycleLabel)) &&
            !selectedFormIds.includes(v.value)
        );
      }
      return newItem;
    })
    .filter((v: any) => v.children && v.children.length > 0);
});
async function initTypeOptions() {
  const category: any = await FormAPI.getFormCategoryList();
  const formDefine: any = await FormAPI.getDefinitionAllList();
  const formDefineList: any[] = [];
  formDefine.map((item: any) => {
    if (item.status == 1) {
      formDefineList.push(item);
    }
  });
  category.forEach((item: any) => {
    const option: any = {};
    option['label'] = item.categoryName;
    option['value'] = item.id;
    option['children'] = formDefineList
      .filter((el: any) => el.categoryId == item.id)
      .map((v: any) => {
        return {
          label: v.formName,
          value: v.id,
        };
      });
    typeOptions.push(option);
  });
}
onMounted(() => {
  initTypeOptions();
  handleQuery();
});
</script>

<style lang="scss" scoped>
.data-content {
  width: 100%;
  height: calc(100vh - 200px);
  display: flex;

  .left {
    width: 280px;
    height: 100%;
    background: #ffffff;
    margin-right: 20px;
    padding: 15px;
  }

  .right {
    width: calc(100% - 280px);
    flex: 1;
    height: 100%;
    background: #ffffff;
  }
}

.title-area {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}
.add {
  padding: 10px 15px;
}
</style>
